package com.mc.cloud.mall.user.service;

import com.mc.cloud.mall.common.exception.MallException;
import com.mc.cloud.mall.common.exception.MallExceptionEnum;
import com.mc.cloud.mall.common.utils.MD5Utils;
import com.mc.cloud.mall.user.model.mapper.UserMapper;
import com.mc.cloud.mall.user.model.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.NoSuchAlgorithmException;

/**
 * @ClassName UserServiceImpl
 * @Author MC
 * @Date 2021/5/20 16:55
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    UserMapper userMapper;
    
    @Override
    public void register(String userName, String password) throws MallException {
        User result = userMapper.selectByName(userName);
        //判断用户名是否为空
        if (result!=null){
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        
        User user = new User();
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        user.setUsername(userName);
        int i = userMapper.insertSelective(user);
        if (i==0){
            throw new MallException(MallExceptionEnum.INSERT_FAILED);
        }
    }
    
    @Override
    public User login(String userName, String password) throws NoSuchAlgorithmException, MallException {
        String md5Str = MD5Utils.getMD5Str(password);
        
        User user = userMapper.selectByNameAndPassword(userName, md5Str);
        if (user==null){
            throw new MallException(MallExceptionEnum.PASSWORD_ERROR);
        }
        
        return user;
        
    }
    
    @Override
    public void update(User user) throws MallException {
        
        int i = userMapper.updateByPrimaryKeySelective(user);
        
        if (i > 1){
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
        
        
    }
    @Override
    public boolean isAdmin(User user){
        return user.getRole().equals(2);
    }
    
    
}